import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

const request = axios.create({
	baseURL: process.env.VUE_APP_BASE_URL
})

const white_list = ['/user/login','/user/loginSms', '/code', '/user/register', '/checkCode']

/* axios 请求拦截器 */
request.interceptors.request.use(config => {
	const { url } = config
	if ( white_list.indexOf(url) >= 0) {
		return config
	}
	config.cancelToken = source.token

	const token = sessionStorage.getItem('token')
	config.headers['Authorization'] = token
	return config

}, e => {
	return Promise.reject(e)
})


// axios 响应拦截器
request.interceptors.response.use(resp => {
	// resp = {data: { code, message, data }, xxx}
	// const data = resp.data
	const { data } = resp
	const { code, message } = data
	if (code === 401) {
		sessionStorage.clear()
		Message.error(message)
		router.push("/login")
		// return Promise.reject(message)
		source.cancel();
		return
	}

	return data
}, e => {
	return Promise.reject(e)
})

export default request